import { UI_Listen, UI_Layer } from '../../config/ui_def'
import { WX_AD_CONFIG, Sdk_Platform, VIVO_AD_CONFIG, OPPO_AD_CONFIG } from '../../frame/constants';
import str from '../tool/str'
import util from '../tool/util';
cc.Class({
    extends: cc.Component,

    properties: {
        describe_lab: cc.Label,
        gold_lab: cc.Label,
        progress_bar: cc.Node,
        progress_lab: cc.Label,
        state_node: cc.Node,
        state_lab: cc.Label,
        getPrice_node: cc.Node,
        icon_sp: cc.Sprite,
        taskNode: cc.Node,
        adNode: cc.Node,
        adIcon: cc.Sprite,
        adTitle: cc.Label,
        adDescribe: cc.Label,

    },

    // LIFE-CYCLE CALLBACKS:

    taskItemInit(info, isAd) {
        if (isAd) {
            this.adSwitch(true)
            this.adNode.active = true
            this.taskNode.active = false
            this.node.active = false
            return
        }
        this.node.active = true
        this.adNode.active = false
        this.taskNode.active = true
        this.taskInfo = info || { type: 1, num: 1, need: 7, awardType: 1, awardNum: 5, isGet: false }
        let itemInfo = he.db.getDataByArgs('Item', { id: parseInt(this.taskInfo.reward.split('#')[0]) })
        this.icon_sp.spriteFrame = he.load.get('item', cc.SpriteAtlas, 'plist').getSpriteFrame(`${itemInfo.id}`)
        this.gold_lab.string = `${this.taskInfo.reward.split('_')[1]}`
        // this.gold_lab.string = `${this.taskInfo.awardNum}`
        this.progress_bar.width = 0
        this.progress_bar.width = 357 / this.taskInfo.need * this.taskInfo.num
        this.progress_lab.string = `${this.taskInfo.num}/${this.taskInfo.need}`
        if (this.taskInfo.num >= this.taskInfo.need) {
            if (this.taskInfo.isGet) {
                this.state_node.active = true
                this.getPrice_node.active = false
                this.state_node.getComponent(cc.Button).interactable = false
                this.setStatePic(false)
                // this.state_lab.string = `已领取`
            } else {
                this.state_node.active = false
                this.getPrice_node.active = true
            }
        } else {
            this.state_node.active = true
            this.getPrice_node.active = false
            this.state_node.getComponent(cc.Button).interactable = true
            // this.state_lab.string = `进行中`
            this.setStatePic(true)
        }
        let taskDec = he.db.getDataByArgs('Task', { type: this.taskInfo.type }).description
        switch (this.taskInfo.type) {
            case 9001:
                // this.describe_lab.string = `观看${this.taskInfo.need}次广告`
                // console.log(taskDec)
                this.describe_lab.string = str.format4Arr(taskDec, [this.taskInfo.need])
                break
            case 9002:
                let monsterInfo = he.db.getDataByArgs('Monster', { monsterId: this.taskInfo.param })
                let name = monsterInfo.name.split('_')[0]
                this.describe_lab.string = str.format4Arr(taskDec, [name, this.taskInfo.need])
                break
            case 9003:
                let roleInfo = he.db.getDataByArgs("Role", { roleId: this.taskInfo.param })
                this.describe_lab.string = str.format4Arr(taskDec, [roleInfo.name, this.taskInfo.need])
                break
            case 9004:
                this.describe_lab.string = str.format4Arr(taskDec, [this.taskInfo.need])
                break
        }
    },
    //true  进行中， false 已完成
    setStatePic(state) {
        let sp = this.state_node.getComponent(cc.Sprite)
        let name
        if (state) {
            name = "zhuangtai_jinxingzhong"
        } else {
            name = 'zhuangtai_yilingqu'
        }
        sp.spriteFrame = he.load.get('taskPage', cc.SpriteAtlas, 'plist').getSpriteFrame(`${name}`)
    },

    //前往
    goTo() {
        switch (this.taskInfo.type) {
            //看完广告后跳转更新页面
            case 9001:
                util.adFakeTip()
                he.ad.showVideo(() => {
                    // gg.eventManager.emit('mission', { type: UI_Listen.TASK_UPDATE })
                    let taskGrp = he.local.getJson('task', 'user')
                    if (taskGrp && taskGrp.length > 0) {
                        for (let j = 0; j < taskGrp.length; j++) {
                            if (taskGrp[j] == 9001) {
                                this.taskInfo = taskGrp[j]
                                if (this.taskInfo.num < this.taskInfo.need) {
                                    this.taskInfo.num += 1
                                }
                                break
                            }
                        }
                        this.taskItemInit(this.taskInfo)
                    }

                })
                break
            //跳转到相应的主页面
            case 9002:
                //根据已通过的关卡怪物列表，找到相应的怪？要是已通过的关卡里没有相应的怪怎么处理- -给提示未解锁最低要求
                let passTeam = he.db.getTable('PassTeam')
                let monGrp = he.db.getTable('Monster')
                let passSort = he.db.getTable('PassSort')
                let lowestPass = 10101
                let monIdGrp = []
                for (let x = 0; x < monGrp.length; x++) {
                    if (monGrp[x].monsterId == this.taskInfo.param) {
                        monIdGrp.push(monGrp[x].id)
                    }
                }
                for (let y = 0; y < passTeam.length; y++) {
                    let isHave = this.passTeamCheck(passTeam[y].teamMenber, monIdGrp)
                    if (isHave) {
                        for (let z = 0; z < passSort.length; z++) {
                            if (passSort[z].teamId == passTeam[y].id) {
                                lowestPass = passSort[z].passId
                                break
                            }
                        }
                        break
                    }
                }
                let len = he.local.getJson('pass_list', 'user').length
                if ((lowestPass - 10100) > len) {
                    gg.uiManager.addTip('未解锁最低要求关卡')
                } else {
                    gg.data.pass_id = lowestPass
                    gg.eventManager.emit('bottomBar', UI_Listen.TASK_TIAOZHUAN, 2)
                }
                break
            //跳转到打的最新的一个关卡
            case 9003:
                let passGrp = he.local.getJson('pass_list', 'user')
                let bigPass = 10101
                if (passGrp && passGrp.length > 0) {
                    for (let i = 0; i < passGrp.length; i++) {
                        if (passGrp[i].id >= bigPass) {
                            bigPass = passGrp[i].id
                        }
                    }
                }
                gg.data.pass_id = bigPass
                gg.eventManager.emit('bottomBar', UI_Listen.TASK_TIAOZHUAN, 2)
                break
            //跳转到装备页面
            case 9004:
                gg.eventManager.emit('bottomBar', UI_Listen.TASK_TIAOZHUAN, 1)
                break
        }
    },

    passTeamCheck(passStr, grp) {
        let idGrp = passStr.split('#')
        let isHave = false
        for (let i = 0; i < idGrp.length; i++) {
            for (let j = 0; j < grp.length; j++) {
                if (grp[j] == parseInt(idGrp[i])) {
                    return true
                }
            }
        }
        return isHave
    },

    getPriceServer() {
        if (this.taskInfo.num >= this.taskInfo.need) {
            // let gold = he.local.getJson('coin', 'user')
            // gold += this.taskInfo.awardNum
            // he.local.setJson('coin', gold, 'user')
            let task = he.local.getJson('task', 'user')
            if (task && task.length > 0) {
                for (let i = 0; i < task.length; i++) {
                    if (task[i].type == this.taskInfo.type && this.taskInfo.need == task[i].need && this.taskInfo.num == task[i].num) {
                        if (this.taskInfo.param && task[i].param) {
                            if (this.taskInfo.param == task[i].param) {
                                task[i].isGet = true
                                break
                            }
                        } else {
                            task[i].isGet = true
                            break
                        }
                    }
                }
                he.local.setJson('task', task, 'user')
            }
            let itemGrp = this.taskInfo.reward.split('_')
            gg.data.addItem(parseInt(itemGrp[0]), parseInt(itemGrp[1]))
            this.getPrice_node.active = false
            this.state_node.active = true
            this.state_node.getComponent(cc.Button).interactable = false
            this.setStatePic(false)
            gg.eventManager.emit('mission', { type: UI_Listen.TASK_UPDATE })
            let info = itemGrp[0] + "_" + itemGrp[1]
            let grp = []
            grp.push(info)
            gg.uiManager.addPage(UI_Layer.Load, {
                name: 'rewardPage',
                itemGrp: grp,
                cover: true,
                close: true,
                gameOver: true,
            })
        }
    },
    clickServer() {
        switch (common.sdk_env) {
            case Sdk_Platform.WECHAT:
                // console.log('clockWXXXXXXX')
                this.wxClilkServer()
                break
            case Sdk_Platform.VIVO:
                he.ad.clickNative(VIVO_AD_CONFIG.nativeAd[3])
                break
            case Sdk_Platform.OPPO:
                break
        }

        // if (this.canClick) {
        // } else {
        // }
    },

    closeServer() {
        this.node.active = false
    },

    adSwitch(status) {
        // this.node.active = true
        if (status) {
            switch (common.sdk_env) {
                case Sdk_Platform.WECHAT:
                    break
                case Sdk_Platform.VIVO:
                    this.vivoAdInit()
                    break
                case Sdk_Platform.OPPO:
                    break
                default:
                    this.node.active = false
                    break
            }
        } else {
            //  关掉广告
        }
    },

    vivoAdInit() {
        let adInfo = he.ad.getNativeJson(VIVO_AD_CONFIG.nativeAd[3], this.successServer.bind(this), this.failServer.bind(this))
        // console.log(adInfo)
        if (!adInfo || adInfo == null || adInfo == undefined) {
            this.failServer()
        } else if (adInfo === true) {

        } else if (adInfo) {
            this.successServer(adInfo)
        }

    },

    successServer(res) {
        // console.log(res, '成功的回调')
        if (!res || res == [] || res == null || res == undefined) {
            this.node.active = false
        } else {
            this.node.active = true
            this.loadImg(this.adIcon, res.imgUrlList[0])
            this.adDescribe.string = `${res.desc}`
            this.adTitle.string = `${res.title}`
        }

    },

    failServer() {
        this.node.active = false
    },

    loadImg(container, url) {
        if (url.length < 4) {
            return he.error(("图片长度不对错误"));
        }
        let ext = url.substring(url.length - 4, url.length)
        ext = ext.toLowerCase()
        if (ext == 'jpeg') ext = '.jpg'
        cc.assetManager.loadRemote(url, { ext: ext }, (err, texture) => {
            if (err) {
                he.error(err)
            }
            if (this.callFun) {
                this.callFun()
            }
            var sprite = new cc.SpriteFrame(texture);
            container.spriteFrame = sprite;
            this.adIcon.node.setContentSize(120, 120)
        });
    },


});
